﻿using MikuMikuModel.Logs;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ft_module_parser.aftconversion.divax
{
    class pvparam_simple
    {
        public static void PVPPProcess(string acpath)
        {
            Logs.WriteLine("PvParam : Processing... ", 0);
            File.WriteAllBytes("__TEMP", ft_module_parser.Properties.Resources.xpvpp);

            if (Directory.Exists(acpath + "\\mdata\\M999\\rom\\pv_param"))
                Directory.Delete(acpath + "\\mdata\\M999\\rom\\pv_param", true);

            System.IO.Compression.ZipFile.ExtractToDirectory("__TEMP", acpath + "\\mdata\\M999\\rom");

            Parallel.ForEach(Directory.EnumerateDirectories(acpath + "\\mdata\\M999\\rom\\pv_param", "*", SearchOption.AllDirectories), new ParallelOptions { MaxDegreeOfParallelism = 8 }, folder =>
            {
                int pvid = int.Parse(Path.GetFileName(folder).Remove(0, 2));

                var files = new List<string>();
                files.Add(folder + "\\stage_light.txt");
                files.Add(folder + "\\chara_light.txt");

                foreach (var file in files)
                {
                    if ((Path.GetFileNameWithoutExtension(file).Contains("stage_light")) || (Path.GetFileNameWithoutExtension(file).Contains("chara_light")))
                    {
                        string[] pvpp = null;
                        pvpp = File.ReadAllLines(file);

                        bool isDone = false;
                        StreamWriter outp = null;
                        while (!isDone)
                        {
                            try
                            {
                                outp = new StreamWriter(file, false, Encoding.ASCII);
                                isDone = true;
                            }
                            catch
                            {
                                Logs.WriteLine("PvParam : Failed! Retrying... " + Path.GetFileNameWithoutExtension(file));
                            }
                        }

                        outp.NewLine = "\n";
                        int ctr = 0;
                        foreach (var i in pvpp)
                        {
                            if (!i.Contains("Type"))
                            {
                                var u = i.Replace(",,,,,0", ",0," + ctr);
                                var str = u.Split(',');
                                outp.WriteLine(u);
                                ctr++;
                            }
                            else outp.WriteLine(i);
                        }
                        outp.Close();
                    }

                    Logs.WriteLine("PvParam : Processed " + file, 1);
                }
            });

            File.Delete("__TEMP");
        }
    }
}
